<template>
  <el-upload
    ref="upload"
    class="upload-demo"
    :limit="1"
    :before-upload="beforeUpload"
  >
    <template #trigger>
      <el-button type="primary">选择文件</el-button>
    </template>
    <el-button class="ml-3" type="success" @click="submitUpload">
      上传
    </el-button>
    <template #tip>
      <div class="el-upload__tip text-red">
        limit 1 file, new file will cover the old file
      </div>
    </template>
  </el-upload>
</template>

<script setup>
  import { ref, onMounted } from "vue"
  import axios from "axios"
  import { useRoute, useRouter } from "vue-router"

  const route = useRoute()
  const router = useRouter()

  const upload = ref(null)

  const chunkSize = 1024 * 1024; // 每片大小 1MB
  const tcount = ref(0);          // 总分片数
  const filename = ref('');       // 文件名
  const file = ref();         // 文件对象
  const uploadAction = 'http://127.0.0.1:8000/orders/file_upload/'; // 替换为你的上传接口

  const beforeUpload = (fileObj) => {
    console.log("uuuuuuuuuuu")
    file.value = fileObj
    console.log(file.value)
    filename.value = fileObj.name
    tcount.value = Math.ceil(fileObj.size / chunkSize)
    return false
  }

  const uploadChunk = async(chunk, chunkindex) => {
    const formData = new FormData()
    formData.append('file', chunk)
    formData.append('filename', filename.value)
    formData.append('count', chunkindex)
    formData.append('tcount', tcount.value)
    formData.append('totalSize', file.value.size)
    const response = await axios.post(uploadAction, formData, {
      headers: {
        Authorization: "Bearer " + localStorage.getItem("access_token")
      }
    })
    return response
  }

  const uploadAllChunks = async() => {
    console.log("kkk")
    for(let i = 0; i < tcount.value; i++) {
      console.log("vvv")
      const start = i * chunkSize
      const end = Math.min(file.value.size, start + chunkSize)
      const chunk = file.value.slice(start, end)

      const uploadResponse = await uploadChunk(chunk, i)
      if(uploadResponse.code !== 200) {
        console.log(`分片${i + 1}/${tcount.value}上传成功`)
      } else if(uploadResponse.code === 10011) {
        console.log(`分片${i + 1}/${tcount.value}上传成功，继续上传`)
      } else{
        alert('分片上传失败')
        return
      }
    }
    console.log('所有分片上传成功')
  }

  const submitUpload = async() => {
    console.log(111)
    await uploadAllChunks()
  }

</script>
